//
//  MJRefresh+Rx.swift
//  live
//
//  Created by melvyn on 2018/11/27.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import MJRefresh
import RxSwift
import RxCocoa

final class MJTarget: NSObject, Disposable {
    
    private var retainSelf: MJTarget?
    var handler: ((MJRefreshComponent) -> Void)?
    var control: MJRefreshComponent
    
    init(control: MJRefreshComponent, handler: @escaping (MJRefreshComponent) -> Void) {
        #if DEBUG
        MainScheduler.ensureExecutingOnScheduler()
        #endif
        
        self.control = control
        self.handler = handler
        super.init()
        self.retainSelf = self

        control.beginRefreshingCompletionBlock = { [weak self] in
            guard let strongSelf = self else {
                return
            }
            handler(strongSelf.control)
        }
    }
    
    func dispose() {
        #if DEBUG
            MainScheduler.ensureExecutingOnScheduler()
        #endif
        self.retainSelf = nil
        control.beginRefreshingCompletionBlock = {}
        handler = nil
    }
}

extension Reactive where Base: MJRefreshComponent {
    
    public var event: ControlEvent<Void> {
        let source = Observable<Void>.create { [weak base](observer) -> Disposable in
            MainScheduler.ensureExecutingOnScheduler()
            
            guard let strongSelf = base else {
                observer.onCompleted()
                return Disposables.create()
            }
            
            let target = MJTarget.init(control: strongSelf, handler: { (_) in
                observer.onNext(())
            })
            return Disposables.create(with: target.dispose)
        }
        .takeUntil(deallocated)
        
        return ControlEvent.init(events: source)
    }
    
    /// Bindable sink for `startAnimating()`, `stopAnimating()` methods.
    public var isAnimating: Binder<Bool> {
        return Binder(self.base) { activityIndicator, active in
            if active {
                activityIndicator.beginRefreshing()
            } else {
                activityIndicator.endRefreshing()
            }
        }
    }
}
